<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: CrazyTobis
  Date: 2020-05-12
  Time: 17:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div id="tcjAddRecept">

    <div class="row col-12">
        <div class= "col-3 form-group">
            <label class="col-form-label"><span style="color: red">*</span>入库类型: </label>
            <select data-tcj="rk-type" class="form-control col-9 " style="display: inline-block">
                <option hidden selected value="">请选择入库类型</option>
                <c:forEach items="${type}" var="obj">
                    <option value="${obj.id}">${obj.name}</option>
                </c:forEach>

            </select>
        </div>

        <div class="col-6 form-group row">
            <label class="col-form-label">入库备注： </label>
               <input data-tcj="remark" class="form-control col-6">

        </div>
        <button class=" btn btn-primary " data-tcj="addRk"><i class="ft-plus-circle" style="font-size: 20px; vertical-align: middle"></i><span style="vertical-align: middle; margin-left: 5px">添加物品</span></button>
        <button class=" btn btn-primary  offset-1" data-tcj="resetRK"><i class="ft-rotate-cw" style="font-size: 20px; vertical-align: middle"></i><span style="vertical-align: middle; margin-left: 5px">重置物品</span></button>

    </div>



    <!--模态框-->
    <div class="modal fade text-center" style="" data-backdrop="static" data-tcj="addRkMode" role="dialog">

        <div class="modal-dialog" role="document"
             style="top: 25px; left: -100px;">
            <div class="modal-content container card" style="width: 800px; margin: 0 auto;">

                <div class="modal-header" style="">
                    <p style="margin: 0 auto; font-weight: 700; font-size: 18px;">选择入库物品</p>
                    <a class="close position-absolute"
                       data-dismiss="modal" aria-label="Close"
                       style="right: 20px;">
                        <span aria-hidden="false">&times;</span>
                    </a>
                </div>

                <div class="modal-body" style="padding: 30px 15px; padding-bottom: 0px;">
                    <%--//这里是表单--%>
                   <form data-tcj="formProduct">
                    <div class="row">
                        <select name="supplierId"  class="cgdd-gys-add col-3 mr-md-3 custom-select form-control" id="ck-add">
                            <option selected hidden value="">请选择供应商</option>
                            <option  value="">全部</option>
                            <c:forEach items="${suplier}" var="obj">
                                    <option value="${obj.id}">${obj.supplierName}</option>
                            </c:forEach>
                        </select>
                        <input name="goodsId" class="col-3 mr-md-3 form-control"
                               placeholder="请输入物品ID" />
                        <input   class="col-3 mr-md-3 form-control"
                               name="goodsName"  placeholder="请输入物品品名" />
                        <button class="col  btn btn-primary "
                                data-original-title="刷新页面时会重置之前的勾选"
                                data-animation="true"
                                data-placement="right"
                                data-toggle="tooltip"
                                data-trigger="hover"
                                data-tcj="rkSelect" type="button" data-toggle="" data-target=""
                                >
                            查询
                        </button>
                    </div>
                   </form>
                        <div class="row" style="margin-top:10px;">
                        <div class="col row justify-content-start">


                        </div>
                    </div>

                    <!--表格的行-->
                    <div class="row">
                        <div class="col " id="tcjAddTable" style="padding: 0;">
                        </div>
                    </div>
                        <%--//这里是按钮--%>

                            <div  data-tcj="click-btn" class="row" >

                            </div>


                </div>


                <div class="modal-footer row justify-content-center">
                    <div class="col">
                        <button class="col-2 btn btn-primary"
                                data-tcj="rkTijiao"
                                type="button"
                                style="margin-left: 20px; height: 37px;">
                            提交
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div data-tcj="add-Table">


       


    </div>


   
</div>
<script src="${pageContext.request.contextPath}/app-assets/js/tooltip.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/app-assets/js/components-modal.min.js" type="text/javascript"></script>

<script>



    (function () {



        //用于储存临时点击的对象
        let objs = [] ;
        //用来储存所有点击的临时对象
        let allobjs =[];
        //点击添加按钮监听
        $('[data-tcj="addRk"]').on("click",function (e) {
            let form = $('[data-tcj="formProduct"]').serialize();


            $.ajax({
                url:"addRecept",
                data:form,
                type:'post',
                dataType:"json",
                async:false,
                success:function (e) {


                    let columns = getColumn(e.data.data,["编号","商品名称","计量单位","品牌","分类","备注","图片"]);
                    columns = skip(columns,"分类","品牌","备注","图片");
                    let options = {
                        key:'goodsName',
                        node:"#tcjAddTable",
                        columns:columns,
                        pageVO:e.data,
                        click:function (clikNode,cloumns,tempDate) {

                            //判断是否点击了全选,这里传入进来的clickNode是null则是点击了全选
                            if(clikNode == "true"){
                                //将tempDate里面的值加到里面
                                for (let o in  tempDate){
                                    let obj = getObj(tempDate[o],cloumns,false,true,false);

                                    //判断临时数组是否有该对象
                                    if(JSON.stringify(objs).indexOf(JSON.stringify(obj)) == -1){
                                        objs.push(obj);
                                    }
                                }
                            }else if(clikNode == "false"){

                                //将临时数组里面的值删除

                                for (let i in tempDate){

                                    let obj = getObj(tempDate[i],cloumns,false,true,false);
                                    //循环判断临时数组是否有该对象有则删除
                                    for(let j in objs){
                                        if(objs[j].id == obj.id){
                                            objs.splice(j,1);
                                        }
                                    }
                                }

                            }else if(clikNode.nodeName === "TR"){

                                //获取当前点击的tr节点的input判断是否选中
                                let input = $(clikNode).find('input');

                                //将该点击的tr转为对象
                                let obj = getObj(clikNode,cloumns,false,true,false);
                                if(input[0].checked){
                                    objs.push(obj);
                                }else {
                                    //如果为选中则将该数据删除
                                    //循环找到该对象，将它删除
                                    for(let i in  objs){
                                        let o = objs[i];
                                        if(o.id == obj.id){
                                            objs.splice(i,1);
                                            break;
                                        }
                                    }
                                }


                            }

                            $('[data-tcj="click-btn"]').html("");
                            for (let o of objs){
                                let btn =   document.createElement("button");
                                $(btn).addClass("btn");
                                $(btn).addClass("btn-primary");
                                $(btn).addClass("mr-5");
                                $(btn).val(o.goodsId);
                                $(btn).text(o.goodsName);

                                $('[data-tcj="click-btn"]').append(btn);
                            }


                        },
                        clickPage:function (e) {

                            //找到全选框
                            let allChecked = $('#tcjAddTable').find("thead").find('input')[0];
                            //找到当前的tbody下的tr
                            //储存是否全选
                            let isAll = true;
                            $(e.node).find("tbody").find("tr").each(function (index,ele) {
                                //找到选择框
                                let input = $(ele).find("input");
                                //将它转为对象
                                let tempObj = getObj(ele,options.columns,false,true,false);
                                //判断是否全选

                                //循环临时数据
                                for (let o of objs){
                                    if(o.id == tempObj.id){
                                        input[0].checked =true;
                                    }
                                }
                                if(!input[0].checked){
                                    isAll = false;
                                }
                            });
                            if(isAll){
                                allChecked.checked = true;
                            }
                        }
                    };

                    $.options = options;

                    firstTable(options);

                }
            });

            //将之前的对象添加到allobjs
            for (let i of objs){
                if(JSON.stringify(allobjs).indexOf(JSON.stringify(objs[i])) == -1){
                    allobjs.push(i);
                }
            }
            objs=[];
            $('[data-tcj="click-btn"]').html("");
            $('[data-tcj="addRkMode"]').modal("show");
        });

        //查询监听
        $('[data-tcj="rkSelect"] ').on("click",function (e) {

            let form = $('[data-tcj="formProduct"]').serialize();

            $.post("addRecept",form,function (e) {
                let options = $.options;
                let pageVO = e.data;
                options.pageVO = pageVO;
                firstTable(options);
            },"json");
            objs=[];
            $('[data-tcj="click-btn"]').html("");
        });

           // 模态框监听
        $('[data-tcj="rkTijiao"]').on('click',function (e) {
                //根据选中的数据生成表格
            //获取需要添加的节点
            let node = $('[data-tcj="add-Table"]');
            //先将objs的数据加到allobjs
            for (let i of objs){
                if(JSON.stringify(allobjs).indexOf(JSON.stringify(objs[i])) == -1){
                    allobjs.push(i);
                }
            }
            //通过ajax查询这些临时数据的数据库数据
            //先将临时数据的id存起来传到servlet
            let ids = [];

            for (let i of allobjs){
                ids.push(i.id);
            }
            //如果临时数组里有值则将数据在数据库查一遍将表格显示
            if(ids.length >0){
                //将这个设置servlet使用getparameterValues能够得数组
                $.ajaxSettings.traditional = true;
                $.post("selectInfo",{"goodsInfo":ids},function (e) {
                    //得到返回的对应的数据库的信息


                    //动态拼接
                    getTable(node,e.data);

                    //监听提交

                    $('[data-tcj="ruku"]').on('click',function () {
                        //找到入库类型
                        let type = $('[data-tcj="rk-type"]')[0].value;
                        //找到备注
                        let remark = $('[data-tcj="remark"]')[0].value;
                        let attrId = "";
                        if(type == ""){
                            alert("请选择入库类型！");
                        }else {
                            //找到表格
                            //用来储存所有添加的商品的对象数组
                            let addAarray = [];
                            //找到表格的下的奇数tr
                            //获取到入库类型
                            let typeId = $('[data-tcj="rk-type"]')[0].value;
                            //获取到入库备注
                            let remark = $('[data-tcj="remark"]')[0].value;
                            $('[data-big="true"]').each(function (index,ele) {

                               //得到它的自定义属性储存的是商品的id
                                let id = $(ele).attr('data-tcj');

                                //得到它下一个兄弟节点
                                let nextTr = $(ele).next();
                                //循环遍历它下面的tr
                                //找到它下面的thead


                                $(nextTr).find('tbody').find('tr').each(function (index,ele) {
                                    //这里思路是先遍历它的td然后得到td的index根据index找thead的值
                                    let num;
                                    $(ele).find('td').each(function (ind,ele) {
                                                //查找该td下是否有select

                                        if($(ele).find('select').length >0){
                                               //如果有则根据index找thead的td的值


                                             $(nextTr).find('thead').find('td ').each(function (tdIndex,ele) {



                                                        if(ind == tdIndex){

                                                            //得到它的自定义属性
                                                            let attr = $(ele).attr('data-tcj');

                                                                //拼attrId
                                                            attrId+=attr+"-";
                                                            return false;

                                                        }
                                             });
                                            //得到该select的值
                                             let selectValue =  $(ele).find('select')[0].value;
                                             attrId+=selectValue;
                                            attrId+=",";

                                        }
                                        //得到入库数量

                                        if($(ele).find('input').length>0){
                                            //得到入库数量
                                             num = $(ele).find('input')[0].value;

                                        }



                                    });
                                    //开始拼添加的对象
                                    let obj = {"goodsId":id,'receptAmount':num,"attrId":attrId.substring(0,attrId.length-1)};
                                    addAarray.push(obj);



                                    attrId = "";
                                })

                            });
                            //创建一个入库单对象
                            let rkObj = {'typeId':typeId,'remark':remark,'goodsInfoDate':addAarray};
                            //传到后端,指定传输json对象

                            $.ajax({
                                dataType:'json',
                                url:'addBill',
                                type:'post',
                                data:JSON.stringify(rkObj),
                                traditional:true,
                                success:function (e) {
                                    console.log(e)
                                    let row = parseInt(e);
                                    if(row > 0){
                                        alert("添加成功!");
                                        $('').returnMianbao();
                                        $.getMenuData('chanpinruku').start($(getShowPane()).find('chanpinruku'));
                                    }
                                }
                            });


                            JSON.stringify(rkObj);
                        }
                    })
                },'json');
            }else {
                alert("没有选中任何商品！");
            }
            $('[data-tcj="addRkMode"]').modal('hide');
            objs=[];
            
        });
        //重置物品监听
        $('[data-tcj="resetRK"]').on('click',function (e) {
                $('[data-tcj="add-Table"]').html("");
                allobjs = [];
                objs = [];
        })
        
        
        function getTable(node,objs) {

            let talbe = `<section id="shopping-cart">
            <div class="row">
                <div class="col-sm-12">
                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title">
                                <%--表格标题--%>
                            </h4>
                        </div>
                        <div class="card-content">
                            <div class="card-body">
                                <table data-tcj="big-table" class="table table-responsive-md text-center">
                                    <thead>
                                    <tr class="xhq-table-color">
                                        <th>编号</th>
                                        <th>物品图片</th>
                                        <th>入库物品名称</th>
                                        <th>物品ID</th>
                                        <th>计量单位</th>
                                        <th>入库数量</th>

                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody>`;
                                let tempbody = ``;
                                let i = 0;
                                for(let o of objs){
                                    //获取到传过来的对象的属性的数组
                                    let types = o.goodsTypes;

                                    i+=1;

                                    tempbody += ` <tr  data-tcj= "\${o.id}" data-big="true">
                                        <td>1</td>
                                        <td>
                                            <div class="card collapse-icon accordion-icon-rotate mr-0 left" style="margin: 0px">
                                                <div id="headingCollapse21" class="">
                                                    <a data-toggle="collapse" href="#tcj\${i}" aria-expanded="true" aria-controls="tcj\${i}" class="card-title lead p-0">
                                                        <img class="media-object round-media" src="static/img/\${o.picture}" alt="通用占位符图像" style="height: 75px;"></a>
                                                </div>
                                            </div>
                                        </td>
                                        <td>\${o.goodsName}</td>
                                        <td>\${o.id}</td>
                                        <td>\${o.unit}</td>

                                        <td data-tcj="num">
                                           0
                                        </td>

                                        <td>

                                            <a class="info mr-3" data-original-title="">
                                                <i class="ft-plus-circle font-medium-3" data-tcj="big-add"></i>
                                            </a>

                                            <a class="danger" data-original-title="" title="">
                                                <i class="ft-trash font-medium-3"data-tcj="big-delete"></i>
                                            </a>

                                        </td>
                                    </tr>



                                    <tr class="xhq-table-color">



                                        <td colspan="9" class="p-0">
                                            <div id="tcj\${i}" role="tabpanel" aria-labelledby="tcj\${i}" class="collapse show">
                                                <div class="card-content">
                                                    <div class="card-body">

                                                        <table class="table table-responsive-md text-center">
                                                            <thead>
                                                            <tr class="">`;
                                                            //循环拼接属性的列名

                                                            for(let i in types){

                                                                tempbody+=` <td data-tcj="\${o.attrId[i]}" style="width: 10%"> \${i}</td>`
                                                            }

                                                    tempbody    +=`

                                                                <td style="width: 10%">入库数量</td>
                                                                <td style="width: 10%">操作</td>
                                                                <td style="width: 10%"></td>
                                                                <td style="width: 10%"></td>
                                                                <td style="width: 10%"></td>
                                                            </tr>
                                                            </thead>
                                                            <tbody>`;
                                                             //循环拼接属性的列
                                                            for(let type in types){
                                                                //获取到改属性名的属性值
                                                                let attr =  types[type];

                                                             tempbody+= "<td><select class='form-control'>";
                                                                        //循环生成select的options
                                                                    for(let attrType of attr){

                                                                        tempbody+=`<option value="\${attrType.id}">\${attrType.attrName}</option>`;
                                                                    }
                                                              tempbody += "</select></td>";
                                                            }
                                                      tempbody +=      `<td >
                                                                <input data-tcj="rk-num" class="form-control" placeholder="入库数量" value="1">
                                                            </td>
                                                            <td >
                                                                <a class="danger" data-original-title="" title="">
                                                                    <i class="ft-trash font-medium-3" data-tcj="small-delete"></i>
                                                                </a>
                                                            </td>
                                                            <td></td>
                                                            <td></td>
                                                            <td></td>

                                                            </tbody>
                                                        </table>

                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>`;
                                };

                                talbe+=tempbody;
                                talbe+=`
                                    </tbody>
                                </table>

                            </div>

                        </div>

                        <div class="card-footer border-0">
                            <div class="row m-0 justify-content-end ">

                                <div class="col-5 row justify-content-end">



                                    <button class="col-2 btn btn-danger float-right" data-tcj="ruku" type="button" >
                                        提交
                                    </button>

                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>`;

                node.html(talbe);

                //监听该表格
          $(node).find('[data-tcj="big-table" ]').on('click',function (e) {


              //得到点击的节点
              let clickNode = e.target;
              //得到该点击的自定义值


               let attr =   $(clickNode).attr('data-tcj');


                if(attr == 'big-add'){
                   //如果是增加属性,找到该点击的tr节点
                   //找到该tr的下一个兄弟节点，然后找到该兄弟节点下的table节点，然后添加一个tr
                    //复制一个节点
                   let tr =  $(clickNode).closest('tr').next().find('tbody').find('tr:last').clone(true);
                        tr.find('input')[0].value = 1;
                   //添加
                   $(clickNode).closest('tr').next().find('tbody').append(tr[0]);

               }else if(attr == 'big-delete'){
                   //如果是删除该商品则将该tr删以及下面第一个兄弟节点删除
                   let tr =  $(clickNode).closest('tr');
                   let parent = $(clickNode).closest('tbody').find('tr[data-big]');
                    console.log(parent)
                   if(parent.length == 1){
                       alert("至少要选择一种商品！");
                       return;
                   }
                   //得到该tr上的自定义属性的值
                   let trAttr = tr.attr('data-tcj');

                   let nextTr = tr.next();
                   tr.remove();
                   nextTr.remove();
                   //同时删除临时数组中的对象
                    //循环遍历判断id找到删除
                   for (let i in allobjs){
                       if(allobjs[i].id == trAttr){
                           allobjs.splice(i,1);
                           break;
                       }
                   }

               }else if(attr == 'small-delete'){
                    let tr =  $(clickNode).closest('tr').siblings();

                    if(tr.length == 0){
                        alert("至少要选择一种属性!");
                        return;
                    }
                    //找到它的tr节点并删除
                    $(clickNode).closest('tr').remove();
                }

                let tempNum = 0;
                if(clickNode.nodeName === 'A' || clickNode.nodeName === 'IMG'){
                    //找到该tr节点
                    let tr = $(clickNode).closest('tr');
                    //找到下一个兄弟节点
                    let nextTR = tr.next();
                    //找到里面的所有input
                   nextTR.find('input').each(function (index,ele) {
                       //获取里面的值
                       let num = parseInt(ele.value);
                       tempNum+=num;

                   });
                    //找到该节点的入库总数
                     tr.find('td').each(function (index,ele) {

                        if($(ele).attr('data-tcj') == 'num'){
                          $(ele).text(tempNum) ;
                          return false;
                        }
                     })
                }


            })




        }
        


    })();

</script>

